package com.mxc.client.splatterclient.configurations;


import com.alibaba.fastjson.JSONObject;
import com.mxc.client.splatterclient.annotations.EnableAuth;
import com.mxc.client.splatterclient.dto.RegisterAuthDto;
import com.mxc.client.splatterclient.dto.RegisterAuthResponseDto;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.stereotype.Component;
import sun.jvm.hotspot.utilities.Assert;

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

@Component
@Slf4j
public class AuthConfiguration implements ImportBeanDefinitionRegistrar {

    private String authServerAddr ;
    private String appKey ;
    private String appName ;


    private static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
    private static final String PROTOCAL_PREFIX = "http://" ;
    private static final String PATH = "/auth/register" ;

    private static  final String OK = "200" ;

    public AuthConfiguration(){

    }

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(importingClassMetadata.getAnnotationAttributes(EnableAuth.class.getName()));
        authServerAddr = annoAttrs.getString("authServerAddr");
        appKey = annoAttrs.getString("appKey");
        appKey = annoAttrs.getString("appName");

        /**注册到权限服务器*/
        RegisterAuthResponseDto registerAuthResponseDto = registerToAuthServer() ;

    }

    private RegisterAuthResponseDto registerToAuthServer() {
        OkHttpClient client = new OkHttpClient();

        try {
            RegisterAuthDto registerAuthDto = RegisterAuthDto.builder()
                    .appKey(appKey)
                    .localIp(InetAddress.getLocalHost().getHostAddress())
                    .build() ;

            String requestUrl = PROTOCAL_PREFIX+authServerAddr+PATH ;

            RequestBody body = RequestBody.create(JSONObject.toJSONString(registerAuthDto), JSON);
            Request request = new Request.Builder()
                    .url(requestUrl)
                    .post(body)
                    .build();

            try (Response response = client.newCall(request).execute()) {
                if(response.isSuccessful()){
                    String responseInfo = response.body().string() ;
                    log.info("授权服务器返回信息: {}",responseInfo);
                    RegisterAuthResponseDto responseDto = JSONObject.parseObject(responseInfo,RegisterAuthResponseDto.class) ;
                    if(OK.equals(responseDto.getCode())){
                        return responseDto ;
                    }else{
                        throw new RuntimeException("注册授权服务器失败，请关注授权服务器返回信息") ;
                    }
                }else{
                    throw new RuntimeException("连接授权服务器异常，请检查配置项是否正确") ;
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("连接授权服务器异常，请检查配置项是否正确") ;
        }

    }
}